// ==UserScript==
// @name        ichaos
// @version     0.10.4
// @include     http://s*.ikariam.*/*
// @include     http://s*.ikariam.*/index.php?view=island&id=*
// @include     http://s*.ikariam.*/index.php?view=militaryAdvisorReportView&combatId=*
// @require	https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js
// @unwrap
// ==/UserScript==

var infoExpiresTime = 1; // время жизни информации топа в часах
var highscoreType = new Array('army_score_main', "trader_score_secondary", 'offense', 'defense');
var Units = {
    slinger:"Пращник",
    swordsman:"Мечник",
    phalanx:"Фаланга",
    marksman:"Стрелок",
    archer:"Лучник",
    cook:"Повар",
    medic:"Доктор",
    steamgiant:"Паровой гигант",
    mortar:"Мортира",
    catapult:"Катапульта",
    ram:"Таран",
    gyrocopter:"Гирокоптер",
    bombardier:"Бомбардировщик"};

var Resources = {wood:"Стройматериалы", wine:"Виноград", marble:"Мрамор", glass:"Хрусталь", sulfur:"Сера"};
var scores = {};
var user, userId, userName;
var server;
var li;
var cookieName;
window.addEventListener("load", init, false);

function init()
{
	switch(document.body.id){
		case "island":island();break;
                case "merchantNavy":merchantNavy();break;
		//case "militaryAdvisorReportView": militaryAdvisorReportView(); break;
	}
}

function island()
{
        $("#cities").click(function(e){
            getGenerals(e);
        })
}

function merchantNavy()
{
    var value,num,img,str;
    $("div.pulldown > div.content").css("height", "43px");
    $("div.payload").each( function(n, tr){
        img = "";
        jQuery.each(Units, function(id, val){
            searchUnits = new RegExp("<img[^src]*src=\"skin\/characters\/military\/x40_y40\/y40_"+id+"_faceright.gif\".+?title=\"(.*?)\"[^>]*>", "i");
            if (searchUnits.test(tr.innerHTML)) {
                value = searchUnits.exec(tr.innerHTML)[1]
                num = parseInt(value);
                img +=  "<img src=\"skin/characters/military/x40_y40/y40_"+id+"_faceright.gif\" width=\"40\" height=\"40\" title=\""+value+"\" alt=\""+val+"\" /> x "+num+" ";
            }
        });
        jQuery.each(Resources, function(id, val){
            searchResources = new RegExp("<img[^src]*src=\"skin\/resources\/icon_"+id+".gif\".+?title=\"(.*?)\"[^>]*>", "i");
            if (searchResources.test(tr.innerHTML)) {
                value = searchResources.exec(tr.innerHTML)[1]
                num = parseInt(value);
                img +=  "<img src=\"skin/resources/icon_"+id+".gif\" width=\"25\" height=\"20\" title=\""+value+"\" alt=\""+val+"\" /> x "+num+" ";
            }
        });
        searchImg = new RegExp("(<img.*>)", "i");
        str = tr.innerHTML;
        tr.innerHTML = str.replace(searchImg, img);
    });
}

function militaryAdvisorReportView()
{
    var arr=["Пращник","Мечник","Фаланга","Лучник","Стрелок","Гирокоптер","Паровой гигант","Бомбардировщик","Мортира","Доктор","Повар","Таран","Катапульта"];
    var a = $("tr.rep > td.units")[0];
	
    $("tr.rep").each( function(n, tr)
    {
        if (n<4)
        {
            searchUnitsTag = /<td class=\"units\"[^>]*>(.*?)<\/td>/mi;
            searchUnits = /<td title=\".+?\"[^>]*>(.*?)[^\(]*\(<span class=\"loss\">-(.*?)<\/span>\)<\/td>/i;
            if (searchUnits.test(tr.innerHTML)) {
                alert(searchUnits.exec(tr.innerHTML)[2]);
            }
            searchColspan = /<td colspan=\"(.*?)\"[^>]*>/mi;
            if (searchColspan.test(tr.innerHTML))
            {
                switch(searchColspan.exec(tr.innerHTML)[1])
                {
                    case "3":
                        break;
                    case "4":
                        break;
                }
            }
        }
    });
}


//window.getGenerals = function(event) {
function getGenerals(event)
{
    var TopInfo = $("#Top_Info");
    if(!TopInfo.attr("id"))
    {
        TopInfo = $("<div></div>").attr("id", "Top_Info").attr("class", "dynamic");
        TopInfo.insertAfter("#infocontainer");
        TopInfo.append($("<h3></h3>").attr("class", "header").text("Баллы"));
        var content = $("<div></div>").attr("class", "content");
        var top_content = $("<ul></ul>").attr("class", "cityinfo").attr("id", "top_content");
        content.append(top_content);
        for (i in highscoreType) {
            if(!$("#"+highscoreType[i]).attr("id"))
                top_content.append($("<li></li>").attr("class", "name").attr("id", highscoreType[i]))
        }
        
        TopInfo.append(content);
        TopInfo.append($("<div></div>").attr("class", "footer"))
    }
    
        /*$("div#information > ul.cityinfo").append('<li id="generals" class="name"></li>');
	$('li#generals').insertBefore('div#information > ul.cityinfo > li.ally');
	$("div#information > ul.cityinfo").append('<li id="sendmessage" class="name"></li>');
	$('li#sendmessage').insertAfter('div#information > ul.cityinfo > li.ally');
	$('div#information > ul.cityinfo > li.owner > a.messageSend').appendTo('li#sendmessage');
	$("div#information > ul.cityinfo > li.ally > a.messageSend").remove();
	$("div#information > ul.cityinfo > li.owner > a.reportPlayer").remove();
    */
	var li;
	if(event.target.parentNode.tagName.toLowerCase() == "a") {
		li = document.getElementById(event.target.parentNode.id).parentNode.id;
	} else {
		li = document.getElementById(event.target.parentNode.id).id;
	}
        
	 var cityinfo = $("#"+li+" > ul.cityinfo > li.owner");
	user = getSearchUser( cityinfo.text() );

        serverReg = new RegExp("s([0-9]+).ru.ikariam.com","mi");
        server = serverReg.exec(document.location.host)[1];
        userNameReg = new RegExp("avatarName=([^\&]+)\&amp\;avatarId=([0-9]+)", "mi");
        var userinfo = $("#"+li+" > ul.cityinfo > li.owner").html();
        
        if (userNameReg.test(userinfo))
        {
            userTEMP = userNameReg.exec(userinfo);
            userName = userTEMP[1];
            userId = userTEMP[2];
            cookieName = server+ '_' + userId;
        }
        else
        {
            cookieName = server + "_my";
        }
	armyTOP = getCookie(cookieName);
//        $("#top_content").html("");
	if(!armyTOP || armyTOP.length > 7) {
		getTopInfo(user);
	} else {
            for (i in highscoreType) {
		returnScore(cookieName, highscoreType[i]);
            }

	}
    
}

function getSearchUser(subject)
{
	searchUserMask = /[^:]+:\s+(.*\S)\s*/m;
	return searchUserMask.exec(subject)[1];
}

function getTopInfo(user)
{
	scores[user] = {};
	scores[user].length = 0;
	for (i in highscoreType) {
		getScore(user, highscoreType[i]);
	}
}

function getScore(searchUser, highscoreType)
{
	var postString = "view=highscore&highscoreType=" + highscoreType + "&searchUser=" + encodeURIComponent(searchUser);
        $.ajax({
                url: '/index.php?'+postString,
                type: "POST",
                cache: false,
                success: function(html){
                    scoreMask = new RegExp('name">' + user.replace(/\s+/g, '\\s+') + '</[^/]+/[\\D]+([\\d.,]+)', 'm');
                    score = scoreMask.exec(html)[1];
                    scoreType = /<option\s+value="(\w+)"\s+selected="selected">/m.exec(html)[1];
//                    alert(scoreType)
                    scores[user][scoreType] = score;
//                    scores[user].length ++;
                            setCookie(cookieName+"_"+scoreType, scores[user][scoreType], infoExpiresTime);
                            returnScore(cookieName,scoreType);
                }
        });
}

function returnScore(cookieName, scoreType)
{
	armyTOP = getCookie(cookieName+"_"+scoreType);
	army = armyTOP.replace(/[.,]/g, '');
        if(scoreType=="army_score_main")
        {
            type = "Генералы";
        }
        if(scoreType=="trader_score_secondary")
        {
            type = "Золото";
        }
        if(scoreType=="defense")
        {
            type = "Баллы защиты";
        }
        if(scoreType=="offense")
        {
            type = "Баллы атаки";
        }
	$('#'+scoreType).html("").append('<span class="textLabel">'+type+': </span>'+ armyTOP);
}

function setCookie(cookieName, cookieValue, liveTime)
{
	cookieExpire = new Date();
	cookieExpire.setTime(cookieExpire.getTime()+liveTime*3600000);
	document.cookie = escape(cookieName) + "=" + cookieValue + "; expires=" + cookieExpire.toGMTString();
}
 
function getCookie (cookieName)
{
        if (document.cookie.length>0)
        {
            c_start=document.cookie.indexOf(cookieName + "=");
            if (c_start!=-1)
            {
                c_start=c_start + cookieName.length+1;
                c_end=document.cookie.indexOf(";",c_start);
                if (c_end==-1) c_end=document.cookie.length;
                return unescape(document.cookie.substring(c_start,c_end));
            }
        }
        return "";
}

//function handler()
//{
//	if(this.readyState == 4)
//	{
//		scoreMask = new RegExp('name">' + user.replace(/\s+/g, '\\s+') + '</[^/]+/[\\D]+([\\d.,]+)', 'm');
//		score = scoreMask.exec(this.responseText)[1];
//		scoreType = /<option\s+value="(\w+)"\s+selected="selected">/m.exec(this.responseText)[1];
//		scores[user][scoreType] = score;
//		scores[user].length ++;
//		if(scores[user].length == highscoreType.length)
//		{
//			setCookie(cookieName, scores[user]['army_score_main'], infoExpiresTime);
//			returnScore();
//		}
//	}
//}

function trim (str)
{
	str.replace(/\s+/mg, ' ');	 
	return str.replace(/\s*(.*)\s*/m, '$1');
}

function str_replace(search, replace, subject) {
    return subject.split(search).join(replace);
}
